import { defineEventHandler, getQuery } from 'h3'
import { recordLog } from '../util/log'

export default defineEventHandler(async (event) => {
  const q = getQuery(event) as { city?: string }
  const city = q.city
  if (!city) {
    event.node.res.statusCode = 400
    await recordLog(event as any, { message: 'weather: missing city query parameter', userId: 0 })
    return { status: 400, message: 'missing city query parameter' }
  }

  try {
    // 在服务器端使用 $fetch 代理外部请求，避免浏览器 CORS 限制
  const data = await fetch(`http://t.weather.itboy.net/api/weather/city/${encodeURIComponent(city)}`).then(r => r.json())
    await recordLog(event as any, { message: `weather: success city=${city}`, userId: 0 })
    return data
  } catch (err) {
    // 返回 502 表示上游服务器错误或无法访问
    event.node.res.statusCode = 502
    await recordLog(event as any, { message: `weather: upstream fetch failed ${String(err)}`, userId: 0 })
    return { status: 502, message: 'upstream fetch failed', error: String(err) }
  }
})
